package easy.环形链表;


import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<>();
        while (head != null) {
            if (!seen.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }

    public static void main(String[] args) {
        // 创建节点
        ListNode n1 = new ListNode(3);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(0);
        ListNode n4 = new ListNode(-4);
        // 连接节点
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n2; // 形成环
        // head 指向第一个节点
        ListNode head = n1;

        ListNode head2 = new ListNode(3, new ListNode(2, new ListNode(0)));
        Solution solution = new Solution();
        System.out.println(solution.hasCycle(head));
        System.out.println(solution.hasCycle(head2));
    }
}
